#!/bin/python3

import os
import sys
import subprocess
import json

macine_arch=""
hjson=json.dumps({'':{}})

def init_hjson(fpath):
    return json.dumps({fpath:{}})

d_include="include"

def read_cfile(fpath):
    dir_name,file_name=os.path.split(fpath)
    hfiles=subprocess.run('git grep "#include" '+fpath+' | awk \'{print$2}\' | sed \'s/[<|>]//g\'', shell=True, stdout=subprocess.PIPE).stdout.decode().split()
    tmpjson={}
    print(fpath)
    print(hfiles)
    for i in hfiles:
        if i[:1] == "\"":
            #"\""开头，到当前目录寻找
            tmpjson.update(read_cfile(dir_name+'/'+i[1:-1]))
        elif i[:5] == "linux" or i[:11] == "asm-generic" or i[:4] == "uapi":
            #include目录
            if dir_name[:12] == "include/uapi":
                thepath_uapi="include/uapi/"+i
                if os.path.exists(thepath_uapi):
                    tmpjson.update(read_cfile(thepath_uapi))
                    continue
                    #tmpjson.update(read_cfile("include/uapi/"+i))
            thepath="include/"+i
            #tmpjson.update(read_cfile("include/"+i))
            tmpjson.update(read_cfile(thepath))
        elif i[:3] == "asm" or i[:8] == "uapi/asm":
            #arch/架构/include/
            if dir_name[:12] == "include/uapi":
                tmpjson.update(read_cfile("arch/"+macine_arch+"/include/uapi/"+i))
            else:
                tmpjson.update(read_cfile("arch/"+macine_arch+"/include/"+i))
    return {fpath:tmpjson}

#分析ffile是否可能被hfile引用
def filter_hfile(hfile, ffile):
    if ffile[:(len(macine_arch)+5)] != "arch/"+macine_arch:
        return False
    hfile_df=os.path.split(hfile)
    ffile_df=os.path.split(ffile)
    if hfile_df[0] == ffile_df[0]:
        return True

def search_hfile(fpath):
    dir_name,file_name=os.path.split(fpath)
    hfiles=subprocess.run('git grep "#include" '+fpath+' | awk \'{print$2}\' | sed \'s/[<|>]//g\'', shell=True, stdout=subprocess.PIPE).stdout.decode().split()
    tmpjson={}
    print(fpath)
    print(hfiles)
    for i in hfiles:
        if i[:1] == "\"":
            #"\""开头，到当前目录寻找
            tmpjson.update(search_hfile(dir_name+'/'+i[1:-1]))
            continue
        #首先根据文件名找到所有对应文件，然后分析可能性最大的文件
        linux_hfile=subprocess.run('find -name '+file_name, shell=True, stdout=subprocess.PIPE).stdout.decode().split()
        for f in linux_hfile:
            if filter_hfile(fpath, f):
                tmpjson.update(search_hfile(f))

    return {fpath:tmpjson}

if __name__=="__main__":
    args=sys.argv
    macine_arch=args[2]
    hjson=init_hjson(args[1])
    h=search_hfile(args[1])
    print(json.dumps(h,indent=4))
